package blog.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;

import blog.entity.Tag;
import blog.mapper.TagMapper;
import blog.service.TagService;

@Service
public class TagServiceImpl implements TagService{
	@Autowired
	private TagMapper tagMapper;
	/**
	 * 查询所有标签
	 */
	public List<Tag> getAllTag() {
		List<Tag> allTag = tagMapper.getAllTag();
		return allTag;
	}
	/**
	 * 根据标签id查询文章数量 利用分页插件进行分页
	 * @param id
	 * @return
	 */
	public PageInfo<Tag> getPageArticleCountByTagId(Integer pageIndex,Integer pageSize) {
		PageHelper.startPage(pageIndex, pageSize);
		List<Tag> allTag = tagMapper.getAllTag();
		for(Tag tag:allTag) {
			List<Integer> ids = tagMapper.getArticleCountByTagId(tag.getTagId());
			if(ids!=null) {
				tag.setArticleCount(ids.size());
			}else {
				tag.setArticleCount(0);
			}
		}
		PageInfo<Tag> pageInfo = new PageInfo<Tag>(allTag);
		return pageInfo;
	}
	
	/**
	 * 根据标签名查询标签
	 * @param tagName
	 * @return
	 */
	public Tag getTagByName(String tagName) {
		return tagMapper.getTagByName(tagName);
	}
	/**
	 * 添加标签
	 * @param tagName
	 * @return
	 */
	public int addTag(Tag tag) {
		return tagMapper.insertTag(tag);
	}
	/**
	 * 根据id删除标签
	 * @param id
	 */
	public void deleteTag(Integer id) {
		tagMapper.deleteTag(id);
		
	}
	/**
	 * 根据id查询标签
	 * @param id
	 */
	public Tag selectTagById(Integer id) {
		return tagMapper.selectTagById(id);
	}
	
	/**
	 * 修改标签
	 */
	public int updateTag(Tag tag) {
		return tagMapper.updateTag(tag);
	}
	/**
	 * 添加文章的标签信息
	 * @param articleId 文章id
	 * @param tagId 标签id
	 */
	public void addArticleTag(Integer articleId, Integer tagId) {
		tagMapper.addArticleTag(articleId,tagId);
	}
	/**
	 * 删除文章时，删除跟文章有关的article_tag_ref表中的数据
	 * @param articleId 文章id
	 */
	public void deleteTagArticle(Integer articleId) {
		tagMapper.deleteTagArticle(articleId);
	}
	/**
	 * 去article_tag_ref表查询出有关的标签id
	 * @param getArticleById
	 */
	public List<Integer> getArticleTag(Integer articleId) {
		return tagMapper.getArticleTag(articleId);
	}

}
